package com.gitee.cheungming.search.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.gitee.cheungming.search.doc.GoodsDocument;
import com.gitee.cheungming.search.reposity.GoodsDocumentRepository;
import com.gitee.cheungming.search.service.GoodsDocumentService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.query.Criteria;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class GoodsDocumentServiceImpl implements GoodsDocumentService {

    @Resource
    GoodsDocumentRepository goodsDocumentRepository;

    @Resource
    ElasticsearchTemplate elasticsearchTemplate;


    @Override
    public List<GoodsDocument> list(String keyword) {
        // 创建查询条件
        Criteria criteria = new Criteria();
        if (StrUtil.isNotBlank(keyword)) {
            criteria = Criteria.where("goodsName")
                    .matches(keyword).and("description").matches(keyword);
        }


        CriteriaQuery query = new CriteriaQuery(criteria);
        query.setPageable(Pageable.ofSize(10).withPage(0));
        SearchHits<GoodsDocument> hits = elasticsearchTemplate.search(query, GoodsDocument.class);
        System.out.println(JSONUtil.toJsonStr(hits));
        return hits.stream().map(SearchHit::getContent).collect(Collectors.toList());

    }
}
